package com.demo.deal_queue;

import com.demo.commons.MqCons;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author shenguangyang
 */
@Component
@RabbitListener(queues = MqCons.DEAL_BIZ_QUEUE)
public class DealBizListener {
    AtomicInteger count = new AtomicInteger(1);
    @RabbitHandler
    public void onMessage(String bizMessage, Channel channel, Message message) {
        try {
            System.out.println(DealBizListener.class.getSimpleName() + ": " + bizMessage);
            if (count.incrementAndGet() % 2 == 0) {
                // 第二个参数，true会重新放回队列，所以需要自己根据业务逻辑判断什么时候使用拒绝
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                return;
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                // channel.basicRecover(true);
            } catch (Exception ex) {
                ex.printStackTrace();
                return;
            }
            e.printStackTrace();
        }
    }
}
